<template>
  <div>
    <el-drawer v-model="drawer" title="合同确认完成" :with-header="true">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="ruleForm"
        label-width="130px"
        class="demo-ruleForm"
      >
        <el-form-item label="合同完成时间：" prop="finishTime">
          <el-date-picker
            v-model="ruleForm.finishTime"
            type="date"
            placeholder="请选择完成时间"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance } from 'element-plus'
  import { putMarketingContract } from '@/api/controller/marketing-contract-controller/index'
  import { putProcurementContract } from '@/api/controller/procurement-contract-controller/index'
  const drawer = ref(false)
  const contractType = ref()
  const show = async (id, type) => {
    ruleForm.value = {
      id: id,
      contractState: '已完成',
      finishTime: '',
    }
    contractType.value = type
    drawer.value = true
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = ref({
    id: null,
    contractState: '已完成',
    finishTime: '',
  })
  const rules = reactive({
    finishTime: [{ required: true, message: '请选择完成时间', trigger: 'blur' }],
  })
  const submit = async (formEl: FormInstance | undefined) => {
    ElMessageBox.confirm('确定该合同履行完毕吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      if (!formEl) return
      formEl.validate(async (valid) => {
        if (valid) {
          let result
          if (contractType.value === '1') {
            result = await putMarketingContract(ruleForm.value, { loading: true })
          } else {
            result = await putProcurementContract(ruleForm.value, { loading: true })
          }
          if (result.code === 200) {
            await emit('getData')
            drawer.value = false
            ElMessage.success('更新成功')
          }
        } else {
          ElMessage.warning('请正确填写表单')
          return false
        }
      })
    })
  }
  const emit = defineEmits(['getData'])
  defineExpose({
    show,
  })
</script>
